#!/bin/bash

f=$1
pdir=$2

if [ $# -lt 2 ]; then
  echo "$0 <subject list file> <patche dir>"
  exit 1
fi

while read s
do

pat=$(echo ''"$s"'' | sed -e 's/\[/\\[/' -e 's/\]/\\]/')

grep -q ''"${pat}"'' commit.all

if [ $? -eq 0 ]; then
   echo "already applyed, skip"
   continue
fi

P=$(ls ${pdir}/*.patch | while read i
do
  sbj=$(./sub.sed "$i")
  if [ "X${sbj}" = "X$s" ]; then
    echo $i
    break
  fi
done)

if [ -n "${P}" ]; then
   echo "Patching ${P} ..."
   echo
   git am -3 "${P}"
   if [ $? -ne 0 ]; then
       echo "git am failed, try patch ..."
       git am --abort
       echo 
       patch -Np1 -i "${P}"
       if [ $? -eq 0 ]; then
          echo "Patch SUCCESS, please commit manually!"
          echo
          exit 0
       else
          echo "Patch failed, Please FIX!!!"
          echo
       	  exit 1
       fi
   fi
else
   echo "not find patch: $s"
   exit 1
fi

done < "$f"
